
function getStyle() {
    return "<style>.no-print{display:none;}</style>";

}

function getHtml(dom) {
    let inputs = dom.querySelectorAll('input');
    let textareas = dom.querySelectorAll('textarea');
    let selects = dom.querySelectorAll('select');

    for (let k in inputs) {
        if (inputs[k].type === "checkbox" || inputs[k].type === "radio") {
            if (inputs[k].checked === true) {
                inputs[k].setAttribute('checked', "checked");
            } else {
                inputs[k].removeAttribute('checked');
            }
        } else if (inputs[k].type === "text") {
            inputs[k].setAttribute('value', inputs[k].value);
        }
    }

    for (let k2 in textareas) {
        if (textareas[k2].type === 'textarea') {
            textareas[k2].innerHTML = textareas[k2].value;
        }
    }

    for (let k3 in selects) {
        if (selects[k3].type === 'select-one') {
            let child = selects[k3].children;
            for (let i in child) {
                if (child[i].tagName === 'OPTION') {
                    if (child[i].selected === true) {
                        child[i].setAttribute('selected', "selected");
                    } else {
                        child[i].removeAttribute('selected');
                    }
                }
            }
        }
    }
    return dom.outerHTML;
}



function init(dom) {
    let content = getStyle() + getHtml(dom);
    writeIframe(content);
}

function toPrint(w, cb) {

    w.onload = function () {
        try {
            setTimeout(function () {
                w.focus();

                if (!w.document.execCommand('print', false, null)) {
                    w.print();
                }

                w.close();
                cb && cb();
            });
        } catch (err) {
            console.log('err', err);
        }
    };
}

function writeIframe(content) {
    let w;
    let doc;
    let iframe = document.createElement('iframe');
    let f = document.body.appendChild(iframe);
    iframe.id = "myIframe";
    iframe.style = "position:absolute;width:0;height:0;top:-10px;left:-10px;";
    w = f.contentWindow || f.contentDocument;
    doc = f.contentDocument || f.contentWindow.document;
    doc.open();
    doc.write(content);
    doc.close();
    toPrint(w, function () {
        document.body.removeChild(iframe);
    });
}

export function printDom(dom) {

    const options = {
        noPrint: '.no-print',
        onStart() {},
        onEnd() {}
    };

    if ((typeof dom) === "string") {
        dom = document.querySelector(dom);
    }

    init(dom);
}
